<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<c:set value="${pageContext.request.contextPath}" var="path" scope="page"/>
<%@ taglib prefix="spring" uri="/WEB-INF/lib/spring.tld"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <base href="<%=path%>">

    <title></title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
</head>


<style type="text/css">


    .bigClass{
        width: 100%;

    }
    .rightClass{
        width: 300px;
        height: 600px;
        float: left;
    }

    .mainDiv {
        width: 900px;
        height: 600px;
    <%--			display: table-cell;--%>
    <%--			vertical-align: middle;--%>
    <%--			background-color: Gray;--%>
        border: 1 solid black;
        float: left;
    }

    .div1{
        width: 100%;
        height: 100%;
        margin: 0 auto;
    <%--			border: 1 solid red;--%>
    }
    .div2{
        width: 100%;
        height: 100%;
    <%--			border: 1 solid  black;--%>
    }
    .div3{
        width: 100%;
        height: 10%;
    <%--			border: 1 solid green;--%>
    }
    .div4{
        width: 100%;
        height: 100%;
    <%--			border: 1 solid yellow;--%>
    }

    .fileNameSpan{
        margin-left: 5px;

    }
    .downloadSpan{
        margin-left: 3px;
        color: #0000ff;
        cursor: pointer;
    }


</style>


<script type="text/javascript" src="${path}/js/ajax-pushlet-client.js"></script>

<script type="text/javascript">

    //        1、当前状态：未开始、预存资金、进行中、已完成
    //        艺术家：未开始、未开始、上传阶段成果、已完成
    //        委托方：未开始、预存资金、通过本阶段、已完成



    var channl = '${channel}';
    var userID = '${curUser.userId}';

    var nick = '${curUser.nickname}';

    $(function(){

        if(nick == 'null' || nick == ''){
            nick = '${curUser.userName}';
        }

    });
    //初始化根路径，解决IE获取根路径不正确问题
    PL.webRoot = "${path}/";
    PL._init();
    enterChat();
    //PL.joinListen('/cuige/he');
    function onData(event) {





        var action = event.get('action');
        var content = 'none action=' + action;
        if (action == 'send') {

            var name = decodeURIComponent(event.get('nick'));
            var userId = decodeURIComponent(event.get('userID'));
            var headPortrait = decodeURIComponent(event.get('headPortrait'));
            var sty = "";
            if(userID == userId){
                sty = 'mymsg ';
            }else{
                sty = '';

            }



            //content = '<span style="'+sty+'">' + name +" " + event.get('sendTime') + '</span><br/> <i>' + decodeURIComponent(event.get('msg'))+ '</i>';

            content = "<li class='"+sty+" clearfix'>";

            content += "<img src=\"${path}/" + headPortrait + "\" width=\"70\" height=\"70\" />";
            content += "       <h3>"+name+"&nbsp;&nbsp;&nbsp;&nbsp;"+ event.get('sendTime') +"</h3>";
            content += "<p>"+decodeURIComponent(event.get('msg'))+"</p>";
            content += "</li>";

        } else if (action == 'enter') {
            content = '<b><i>*** ' + decodeURIComponent(event.get('nick')) + ' <spring:message code="chatMain.message.msg2" />  ***</i></b>';
        } else if (action == 'exit') {
            content = '<b><i>*** ' + decodeURIComponent(event.get('nick')) + ' <spring:message code="chatMain.message.msg3" />  ***</i></b>';
        }


        $("#chatMsgUl").html($("#chatMsgUl").html() + content);

        $("#member_mroom_list").scrollTop($("#member_mroom_list").get(0).scrollHeight);
        // 离开
        // PL.leave();
    }





    function enterChat(){

        p_join_listen(channl);

        p_publish(channl, 'action', 'enter', 'nick', encodeURIComponent(encodeURIComponent(nick)),
                'userID',userID,'headPortrait',encodeURIComponent(encodeURIComponent('${curUser.headPortrait}')));

    }

    function sendMsg(){


        var msg = $("#sendMsgDiv").val();
        if(attachmentArr.length != 0){

            msg += "<br/>" + $.trim(attachmentArr.join(" "));

        }
        msg = encodeURIComponent(encodeURIComponent(msg));

        p_publish(channl, 'action', 'send', 'nick', encodeURIComponent(encodeURIComponent(nick)),
                'msg', msg,'userID',userID,'headPortrait',encodeURIComponent(encodeURIComponent('${curUser.headPortrait}')));
        resetForm();

        //清空附件框
        attachmentArr = new Array();
        $("#attachmentUl").html("");

    }

    function leaveChat(){
        // Send exit to chatters
        p_publish(channl, 'action', 'exit', 'nick', nick);

        // Stop pushlet session
        p_leave();

        // Give some time to send the leave request to server
        setTimeout('gotoEnter()', 500);
    }

    function gotoEnter() {
        window.location.href='${path}/login.jsp';
    }

    function resetForm(){

        $("#sendMsgDiv").val("");
    }

    //附件数组，用来存需要发送的信息
    var attachmentArr = new Array();

    //Ajax文件上传
    function f_file_upload(){


        //var result =/\.[^\.]+/.exec($("#fulAchievements").val());

        var path = $("#fulAchievements").val();

        var pos1 = path.lastIndexOf("\\");
        var pos2 = path.lastIndexOf(".");
        var pos = path.substring(pos1 + 1, pos2);

        var fileName = path.substring(pos1+1,pos2);

        var str = $("#fulAchievements").val().split(".");
        var result = path.substring(pos2 + 1,path.length );

        var rars = ".rar.zip.7z.cab.txt.doc.docx.xls.xlsx.RAR.ZIP.7Z.CAB.TXT.DOC.DOCX.XLS.XLSX";

        var imgs = ".bmp.jpg.dib.jpeg.png.jfif.jpe.tif.tiff.gif.BMP.JPG.DIB.JPEG.PNG.JFIF.JPE.TIF.TIFF.GIF";

        //文件类型 false为压缩包
        var boo = false;

        if(rars.indexOf(result) > -1){
//                console.log("压缩包");
        }else if(imgs.indexOf(result) > -1){
            boo = true;
//                console.log("图片");
        }else{

            alert("<spring:message code='chatMain.message.msg4' />")
            $("#fulAchievements").val("");
            return;
        }



//            if($("#fulAchievements").val() == ""){
//
//                $.messager.alert('提示','请选择需要上传的文件！');
//                return;
//            }

        $.ajaxFileUpload({
            url: '${path}/fileUpload/upload_resource_file.html',
            secureuri: false,
            fileElementId: 'fulAchievements',
            //dataType: 'json',
            success: function (data) {
                //data = $.parseJSON(data);

                var data2 = data.split(",");

                var url = data2[0].replace(" ","");
                fileName = data2[1].replace(" ","");

                //设置发送内容
                var attachmentArrLength = attachmentArr.push( "<span class='fileNameSpan' value='"+url+"'>"+fileName+ "<a class='downloadSpan' href='${path}/fileDownload/download_file.html?res_url="+url+"'><spring:message code="chatMain.message.msg5" /></a>" +"</span>");



                var src = "${path}/style/common/images/yasuobao.png";
                if(boo){
                    src = "${path}/"+url;
                }

                var html = "";

                html += "<li>";
                html += "<em class='ico_del' onclick=\"f_removeAttchment('"+(attachmentArrLength - 1)+"',this)\">×</em>";
                html += "<img src='"+src+"' width='56' height='70' />";
                html += "        <p>"+fileName+"</p>";

                html += "</li>";

                $("#attachmentUl").html($("#attachmentUl").html() + html);

            },
            error:function(data){

                console.log("error");
                console.log(data);
            }
        });
    }
    //根据附件数组下标删除元素
    function f_removeAttchment(item,obj){

        //把数组元素赋空值
        attachmentArr[item] = "";

//        console.log($(obj).parent());
        //删除元素
        $(obj).parent().remove();


    }





    //查询聊天记录
    function f_findChatInfo(obj){

        if($(obj).html() != "<spring:message code='chatMain.message.msg6' />"){
            return;
        }

        $.post("${path}/chatManage/findChatingRecordList.html",{channel:channl},
                function(data, textStatus, jqXHR){
                    var html = "";

                    for(var i in data){

                        var info = data[i];


                        var sty = "";
                        if(userID == info.userId){
                            sty = 'mymsg ';
                        }else{
                            sty = ''

                        }



                        html += "<li class='"+sty+" clearfix'>";

                        html += "<img src=\"${path}/" + info.headPortrait + "\" width=\"70\" height=\"70\" />";
                        html += "       <h3>"+info.sendUserName+"&nbsp;&nbsp;&nbsp;&nbsp;"+ info.dataTime +"</h3>";
                        html += "<p>"+info.massage+"</p>";
                        html += "</li>";

                    }

                    if(data != null && data != ""){
                        $(obj).html("<spring:message code='chatMain.message.msg7' />");

                    }else{

                        $(obj).html("——————无历史聊天记录——————");

                    }


                    $(obj).css("color","");
                    $("#chatMsgUl").html(html + $("#chatMsgUl").html() );





                });
    }


</script>

</head>

<body >

<div class="member_mroom_box noborder_top mb10">
    <div class="member_mroom_list" id="member_mroom_list" style="overflow-y: auto; height: 500px;">
        <ul id="chatMsgUl">
            <li style="text-align: center;"><a  onclick="f_findChatInfo(this)" style="color: #0000ff;" href="javascript:void(0);"><spring:message code="chatMain.message.msg8" /></a></li>
        </ul>
    </div>
</div>
<div class="member_mroom_file">
    <ul class="clearfix" id="attachmentUl">

    </ul>
    <input type="button" name="" onclick="javascript:$(this).next().trigger('click')" class="btn_addfile" value="<spring:message code='chatMain.message.msg9' />" />
    <input style="display: none" type="file" name="file" id="fulAchievements" onchange="f_file_upload()">
    <input type="hidden" name="attachment" id="attachment" value="">
</div>
<div class="member_mroom_form clearfix">
    <form action="#" onSubmit="sendMsg(); return false;">
        <textarea  id="sendMsgDiv" name="" class="text738"></textarea>
        <input type="button" id="" onclick="sendMsg();" name="" value="<spring:message code='chatMain.message.msg10' />" class="btn_post h122" />
    </form>
</div>
</body>
</html>
